import React, { FC, ReactElement, isValidElement, ReactNode } from 'react';
import { Table, Tag, Space } from 'antd';
import type { TableProps, ColumnsType, ColumnProps } from 'antd/es/table';
import './index.less';

export type ColumnType = {
  title: string;
  dataIndex: string;
  key: string;
  ellipsis: boolean;
  // eslint-disable-next-line no-unused-vars
  render: <T, S>(params1?: T, params2?: S) => ReactElement | ReactNode;
}

type DataType = {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
}

type STableProps = {
  title: string | ReactElement;
  dataSource: Array<Partial<DataType>>;
}

const defaultColumns: Array<Partial<ColumnProps<ColumnsType<ColumnType>>>> = [
  {
    title: 'Name',
    dataIndex: 'name',
    key: 'name',
    render: text => <a>{text}</a>,
  },
  {
    title: 'Age',
    dataIndex: 'age',
    key: 'age',
  },
  {
    title: 'Address',
    dataIndex: 'address',
    key: 'address',
  },
  {
    title: 'Tags',
    key: 'tags',
    dataIndex: 'tags',
    // @ts-ignore
    render: (_, { tags }: { tags: [] }) => (
      <>
        {tags.map((tag: string) => {
          let color = tag.length > 5 ? 'geekblue' : 'green';
          if (tag === 'loser') {
            color = 'volcano';
          }
          return (
            <Tag color={color} key={tag}>
              {tag.toUpperCase()}
            </Tag>
          );
        })}
      </>
    ),
  },
  {
    title: 'Action',
    key: 'action',
    // @ts-ignore
    render: (_, record: { name: '' }) => (
      <Space size="middle">
        <a>Invite {record.name}</a>
        <a>Delete</a>
      </Space>
    ),
  },
];

const defaultData: DataType[] = [
  {
    key: '1',
    name: 'John Brown',
    age: 32,
    address: 'New York No. 1 Lake Park',
    tags: ['nice', 'developer'],
  },
  {
    key: '2',
    name: 'Jim Green',
    age: 42,
    address: 'London No. 1 Lake Park',
    tags: ['loser'],
  },
  {
    key: '3',
    name: 'Joe Black',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
    tags: ['cool', 'teacher'],
  },
];

type filterProps = 'title';

const STable: FC<Partial<STableProps> & Omit<TableProps<any>, filterProps>> = (props): ReactElement => {
  const { title, columns, dataSource, ...tableProps } = props;

  return <>
    <Table
      bordered
      loading={!!dataSource?.length}
      className="base-component-super-table"
      title={() => isValidElement(title) ? title : <h3 className="super-table-title">{title}</h3>}
      columns={columns || defaultColumns}
      dataSource={dataSource || defaultData}
      { ...tableProps }
    />
  </>
};

export default STable;
